/*!
 *
 * Copyright (c) 2019, zhang jianchun.
 * Released under the MIT License.
 */


class media {
    constructor(constraints = {
        /*
         * 约束对象 可以设置精确值[width:640] 理想值 可接受的值范围和/或想要尽可能接近的值 width: { min: 640, ideal: 1920, max: 1920 },
         */
        audio: {
            sampleSize: 16, //样本数
            channelCount: 2, //声道数
        },
        video: {
            aspectRatio: {
                ideal: 1.777777778, // 16:9比例优先
                frameRate: { max: 30 }, //帧
                facingMode: { exact: "user" }, //设配 自拍摄像头
            }
        }
    }) {
        this.constraints = constraints
        // 屏幕对象
        this.displayMedia = {
            stream: null,
            constraints: constraints
        };

        // 摄像头对象
        this.userMedia = {
            stream: null,
            constraints: constraints
        };

        /*
         *设配列表 如：相机和麦克风
         *
         */
        this.enumerateDevices = null


        /*
         * 获取可修改的约束对象
         *
         */
        this.getSupportedConstraints = null

        this.isgetUserMedia = 'getUserMedia' in navigator.mediaDevices
        this.isgetDisplayMedia = 'getDisplayMedia' in navigator.mediaDevices

        navigator.mediaDevices.ondevicechange = function(event) {
            console.log(ondevicechange)
            this.updateDeviceList();
        }
    }
    updateDeviceList() {
        console.log('updateDeviceList')
        let audioList = document.getElementById("audioList");
        let videoList = document.getElementById("videoList");
          navigator.mediaDevices.enumerateDevices()
          .then(function(devices) {
            audioList.innerHTML = "";
            videoList.innerHTML = "";
            
            devices.forEach(function(device) {
              let elem = document.createElement("li");      
              let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i);
              
              elem.innerHTML = "<strong>" + device.label + "</strong> (" + direction + ")";
              if (type === "audio") {
                audioList.appendChild(elem);
              } else if (type === "video") {
                videoList.appendChild(elem);
              }
            });
          });
    }
    init() {

        if (navigator.mediaDevices && navigator.mediaDevices.getSupportedConstraints) {
            this.getSupportedConstraints = navigator.mediaDevices.getSupportedConstraints();
        }

        if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
            navigator.mediaDevices.enumerateDevices().then((devices) => {
                    this.enumerateDevices = devices
                })
                .catch((err) => { console.log(err.name + ": " + err.message); });
        }


    }
    async getUserMedia(constraints = this.constraints) {
        if (this.userMedia.stream) {
            alert('有已经打开的设配，请先关闭')
            return this.userMedia.stream
        }
        try {
            return this.userMedia.stream = await navigator.mediaDevices.getUserMedia(constraints);
        } catch (e) {
            console.error('getUserMedia: ', e)
            console.trace(e)
        }
    }
    async getDisplayMedia(constraints = this.constraints) {
        if (this.displayMedia.stream) {
            alert('有已经打开的设配，请先关闭')
            return this.displayMedia.stream
        }
        try {
            return this.displayMedia.stream = await navigator.mediaDevices.getDisplayMedia(constraints);
        } catch (e) {
            console.error('getUserMedia: ', e)
            console.trace(e)
        }
    }

    /*
     * 调整约束
     * track 轨道
     * constraints 要设置的属性对象
     *
     */
    applyConstraints(track, constraints = {}) {
        track.applyConstraints(constraints);
    }

    /*
     * 获取用户设置约束属性的值
     *
     */
    getSettings(track) {
        return track.getSettings();
    }

    /*
     * 获取可约束属性
     *
     */
    getConstraints(track) {
        return track.getConstraints();
    }
    /*
     * 关闭
     *
     */
    stop(stream) {
        stream.getTracks().forEach(track => {
            track.stop();
        });
        stream = null
    }
    /*
     *关闭user
     */
    stopUserMedia() {
        this.stop(this.userMedia.stream)
    }
    /*
     *单独关闭user音频
     */
    stopUserMediaAudio() {
        this.userMedia.stream.getAudioTracks().forEach(track => {
            track.stop();
        });
    }
    /*
     *单独关闭user视频
     */
    stopUserMediaVideo() {
        this.userMedia.stream.getVideoTracks().forEach(track => {
            track.stop();
        });
    }
    /*
     *关闭Display
     */
    stopDisplayMedia() {
        this.stop(this.displayMedia.stream)
    }
    /*
     *关闭Display音频
     */
    stopDisplayMediaAudio() {
        this.displayMedia.stream.getAudioTracks().forEach(track => {
            track.stop();
        });
    }
    /*
     *关闭Display视频
     */
    stopDisplayMediaVideo() {
        this.displayMedia.stream.getVideoTracks().forEach(track => {
            track.stop();
        });
    }

    iofo() {
        this.userMedia.stream.getTracks().forEach(track => {
            console.log(track)
        })
    }

}